import 'package:flutter/material.dart';
import 'package:flutter_vant_kit/widgets/addressList.dart';
import 'package:provider/provider.dart';
import 'package:shoes_shop/api/api.dart';
import 'package:shoes_shop/core/utils.dart';
import 'package:shoes_shop/models/public_provider_model.dart';
import 'package:shoes_shop/pages/userInfo/addressList/editAddress/edit_address_page.dart';

import 'address_list_provider.dart';

class AddressListPage extends StatelessWidget {
  final bool isSelect;
  const AddressListPage({Key key, this.isSelect = false}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    _getAddressList(context);
    return Scaffold(
      appBar: AppBar(
        // backgroundColor: AppColors.purplishBlue,
        title: Text('地址列表'),
        actions: isSelect?[
          IconButton(
              icon: Icon(Icons.check),
              onPressed: () {
                Navigator.pop(context);
              })
        ]:[],
      ),
      body: Consumer<AddressListProvider>(builder: (context, provider, child) {
        return new AddressList(
          showCheck: isSelect,
          switchable: isSelect,
          index: provider.index, // 选中的index
          list: provider.addressList,
          disabledText: '',
          onEdit: (AddressInfo info, int i) => {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => EditAddressPage(info: info),
              ),
            ).then(
              (value) => {_getAddressList(context)},
            ),
          },
          onAdd: () => {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => EditAddressPage(),
              ),
            ).then(
              (value) => {_getAddressList(context)},
            ),
          },
          onSelect: (info, i) => {provider.changeIndex(i)},
        );
      }),
    );
  }
}

_getAddressList(context) async {
  String openid = Provider.of<PublicProviderModel>(context, listen: false)
      .userInfo['openid'];
  Map res = await getAddressList(openid);

  if (res['code'] == 200) {
    List<AddressInfo> arr = [];
    List val = res['data'];
    for (int i = 0; i < val.length; i++) {
      arr.add(
        AddressInfo(
          id: val[i].sId,
          name: val[i].name,
          tel: val[i].tel,
          province: val[i].province,
          city: val[i].city,
          county: val[i].county,
          provinceId: val[i].provinceId,
          cityId: val[i].cityId,
          countyId: val[i].countyId,
          addressDetail: val[i].addressDetail,
          postalCode: val[i].postalCode,
          isDefault: val[i].isDefault,
        ),
      );
    }
    Provider.of<AddressListProvider>(context, listen: false).changeValue(arr);
  } else {
    showToast(res['message']);
  }
}
